package com.sqlloader.views.listeners;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.sqlloader.db.ConnectionPool;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.IWorkbenchPage;

import com.sqlloader.activator.Activator;
import com.sqlloader.views.DBAccessView;
import com.sqlloader.views.LoadDataView;

public class ColumnComboListener implements Listener,SelectionListener
{
	private CCombo combo;
	private int index;
	public ColumnComboListener(CCombo combo,int index)
	{
		this.combo=combo;
		this.index=index;
	}
	public void handleEvent(Event event) {
	   if(event.type==SWT.FocusIn)
	   {
		   handleFocusIn(event);
	   }
	}
	public void handleFocusIn(Event event) {
		// TODO Auto-generated method stub
		IWorkbenchPage workbenchPage = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
		DBAccessView view=(DBAccessView)workbenchPage.findView("com.sqlloader.views.DBAccessView");
		String dw=view.getDwText().getText();
		String username=view.getUsernameText().getText();
		String tablename=view.getTableCombo().getText();
		if(dw!=null&&!"".equals(dw)){
		try {
			Connection c=ConnectionPool.getInstance().getConnection(dw);
			DatabaseMetaData metadata=c.getMetaData();
			ResultSet rs=metadata.getColumns(null, username.toUpperCase(), tablename.toUpperCase(), null);
			combo.removeAll();
			while(rs.next())
			{
				combo.add(rs.getString("COLUMN_NAME"));
			}
			rs.close();
			c.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		}
		
	}
	
	
	public void widgetDefaultSelected(SelectionEvent event) {
		// TODO Auto-generated method stub
		
	}
	public void widgetSelected(SelectionEvent event) {
		// TODO Auto-generated method stub
		IWorkbenchPage workbenchPage = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
		LoadDataView loaddataview=(LoadDataView)workbenchPage.findView("com.sqlloader.views.LoadDataView");
		String text=((CCombo)event.getSource()).getText();
		loaddataview.getTableViewer().getTable().getColumn(this.index).setText(text);
	}

}
